<?php

namespace app\controllers;

use Yii;
use YiiBase;
use yii\rbac\Item;
use yii\rbac\Role;
use yii\rbac\Permission;
use app\models\Menu;
use app\models\MenuSearch;
use yii\web\Controller;
use yii\web\Request;
use yii\web\Response;
use helper\SessionHelper;
use helper\MenuHelper;

class MenuController extends SecBaseController
{
    public function actionList(){
        $request = Yii::$app->request;
        
        try{ 
            $menuSearch = new MenuSearch();
            $dataProvider = $menuSearch->search($request->getQueryParams());
            $menus = $dataProvider->getModels();
            $menu_data_list = array();
            foreach($menus as $menu) {
                if ($menu->menuParent) {
                    $menu->parent_name = $menu->menuParent->name;
                }
                $menu_data = array( "parent_name" => $menu->parent_name);//不在数据库字段，特殊处理
                $menu_data = array_merge($menu_data, (array)($menu->getAttributes()));
                $menu_data_list[] = $menu_data;;
            }

            //compose table data
            $page = array("page_code" => 1, "data_count" => count($menu_data_list), "page_size" => count($menu_data_list), "first" => 1, "last" => count($menu_data_list), "page_count" => 1, "startNum" => 0, "page_code_list" => array(1), "firstPage" => true, "lastPage" => true  );
            $title_name = array("key" => "name", "name" => "菜单名称", "type" => "text", "editable" => 1, "intable" => 1, "sort_code" => "0", "is_must" => 1, "show_key" => null);
            $title_parent = array("key" => "parent_id", "name" => "父菜单名称", "type" => "enum", "customMap"=>array("url"=>"/basedata/adminmenus", "option_value" => "id", "option_text" => "name", "default_value" => "", "default_name"=> "无"), "editable" => 1, "intable" => 1, "sort_code" => "1", "show_key" => "parent_name");
            $title_route = array("key" => "route", "name" => "菜单路径", "type" => "enum", "customMap"=>array("url"=>"/menu/allroutes", "option_value" => "id", "option_text" => "name", "default_value"=>"", "default_name"=> "无"), "editable" => 1, "intable" => 1, "sort_code" => "2", "show_key"     => "route");
            $title_order = array("key" => "order", "name" => "顺序", "type" => "number", "editable" => 1, "intable" =>1, "sort_code" => null, "show_key" => null);
            $column_title = array($title_name, $title_parent, $title_route, $title_order);

            $data = array("data_name" => "menu", "data_key" => "menu_id", "page" => $page, "column_title" => $column_title, "data_list" => $menu_data_list, "sort_code" => 0, "sortorder" => "desc");
            $this->return_page_values = array_merge($this->return_page_values, $data);
        }catch(\Exception $e){
            $this->return_page_values['errno'] = $e->getCode();
            $this->return_page_values['errmsg'] = $e->getMessage();
            return $this->myRenderFile('@tpl/page/error.tpl', $this->return_page_values);
        }

        //return  json_encode($this->return_page_values);
        return $this->myRenderFile('@tpl/page/menu/list.tpl', $this->return_page_values);

    }

    public function actionCreate(){
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;


        $request = Yii::$app->request;
        //return $request->post();
        try {
            $model = new Menu;
            //$model->load($request->post());
            $model->setAttributes($request->post());
            if ($model->save()) {
                MenuHelper::invalidate();
            } else {
                return ["errno" => -1, "errmsg" => "save model failed: ".json_encode($model->getErrors())];
            }
        }catch(\Exception $e){
            $this->return_page_values['errno'] = -1;
            $this->return_page_values['errmsg'] = 'add role child failed: '.$e->getMessage();
            return $this->return_page_values;
        }

        //$this->return_page_values['errno'] = 0;
        //return $this->return_page_values;
        $ret = array("errno" => 0);
        return $ret;
    }
    
    public function actionUpdate(){
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $request = Yii::$app->request;
        $menu_id = $request->get('menu_id');
        $model = $this->findModel($menu_id);
        if ($model->menuParent) {
            $model->parent_name = $model->menuParent->name;
        }
        $model->setAttributes($request->post());
        if ($model->save()) {
            MenuHelper::invalidate();
        } else {
            return ["errno" => -1, "errmsg" => "update model failed: ".json_encode($model->getErrors())];
        }

        $ret = array("errno" => 0);
        return $ret;
    }

    public function actionDelete(){
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $request = Yii::$app->request;
        $id = $request->get('menu_id'); 
        $this->findModel($id)->delete();
        MenuHelper::invalidate();

        $ret = array("errno" => 0);
        return $ret;
        
    }

    public function actionAllroutes(){
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $result = [];
        foreach (Yii::$app->getAuthManager()->getPermissions() as $name => $value) {
            if ($name[0] === '/' && substr($name, -1) != '*') {
                $result[] = array("id" => $name, "name" => $name);
            }
        }
        return array("data_list" => $result);
    }
    /**
     * Finds the Menu model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param  integer $id
     * @return Menu the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Menu::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
 
}
